//
//  MeHeaderView.swift
//  scfriend
//
//  Created by wulanzhou on 2017/8/31.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

import UIKit

class MeHeaderView: UIView {

    typealias ReachtopBlock = (_ reachtop:Bool) -> ()
    typealias PressHeaderBlock = () -> ()
    
    var kHeaderWidth:CGFloat = 100 // 头像宽度
    var kHeaderMinWidth:CGFloat = 40 // 头像在顶部时的宽度
    
    var block:ReachtopBlock?
    var pressBlock:PressHeaderBlock?
    
    
    
    private lazy var backgroundImageView:UIImageView = {
        
        let bgImageView:UIImageView = UIImageView.init(frame: self.bounds)
        bgImageView.contentMode = .scaleToFill
        bgImageView.clipsToBounds = true
        //[self addSubview:_backgroundImageView];
        return bgImageView
    
    }()
    private lazy var  headerImageView:UIImageView = {
        
        let bgImageView:UIImageView = UIImageView.init()
        bgImageView.backgroundColor = UIColor.clear
        bgImageView.size = CGSize(width: self.kHeaderWidth, height: self.kHeaderWidth)
        bgImageView.center = CGPoint(x:self.bounds.size.width / 2, y:self.bounds.size.height / 2)
        bgImageView.layer.cornerRadius = self.kHeaderWidth / 2
        bgImageView.clipsToBounds = true
        //[self addSubview:bgImageView];
        return bgImageView
    
    }()
    private lazy var label:UILabel = {
    
        let lab:UILabel = UILabel.init()
        lab.backgroundColor = UIColor.clear
        lab.textColor = UIColor.white
        lab.font = UIFont.systemFont(ofSize: 14.0)
        lab.textAlignment = .center
        lab.size = CGSize(width:self.bounds.size.width, height:20)
        lab.centerY = self.bounds.size.width / 2;
        lab.top = self.headerImageView.bottom + 5;
        //[self addSubview:lab];
        return lab
    }()
    /**
     * @property navigationBarHeaderImageView: 当滚动视图滚动到顶部的时候如果有navigationBar则将这个视图添加到navigationBar上
     */
    private lazy var navigationBarHeaderImageView:UIImageView = {
        
        let navBarHeaderImageView:UIImageView = UIImageView.init()
        navBarHeaderImageView.backgroundColor = UIColor.clear
        navBarHeaderImageView.image = self.headerImageView.image?.copy() as? UIImage
        //navBarHeaderImageView.image = self.headerImageView.image?.copy
        navBarHeaderImageView.size = CGSize(width:self.kHeaderMinWidth, height:self.kHeaderMinWidth)
        navBarHeaderImageView.layer.cornerRadius = self.kHeaderMinWidth / 2
        navBarHeaderImageView.clipsToBounds = true
        return navBarHeaderImageView
    
    }()
    /**
     * @property aboveHeaderView: 覆盖在headerImageView上的透明视图, 在上面添加点击手势
     */
    private lazy var aboveHeaderView:UIView = {
        
        let abHeaderView:UIView = UIView.init()
        abHeaderView.backgroundColor = UIColor.clear
        abHeaderView.size = CGSize(width:self.kHeaderWidth,height:self.kHeaderWidth)
        abHeaderView.center = CGPoint(x:self.bounds.size.width / 2, y:self.bounds.size.height / 2)
        return abHeaderView
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.backgroundImageView)
        self.addSubview(self.headerImageView)
        self.addSubview(self.label)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    /** 设置背景图像
     * @param image: 背景图
     */
    func setBackgroundImage(image:UIImage){
       self.backgroundImageView.image = image
    }
    
    
    /** 设置头像及描述文字
     * @param image: 头像
     * @param text: 描述文字
     */
    func setHeader(image:UIImage,text:String) {
    
        self.headerImageView.image = image
        self.label.text = text
    }
    
    /** 根据滚动视图更新视图效果
     * @param scrollView: 滚动视图
     */
    func reloadWithScrollView(scrollView:UIScrollView){
        
        let offsetY:CGFloat = scrollView.contentOffset.y + self.bounds.size.height - kNavigationBarHeight
        if (offsetY < 0) {
            // 下拉
            // 图片放大
            let centerX:CGFloat = self.bounds.size.width / 2
            let centerY:CGFloat = (self.bounds.size.height - offsetY) / 2
            let kScale:CGFloat = (self.bounds.size.height - offsetY) / self.bounds.size.height
            self.backgroundImageView.center = CGPoint(x:centerX, y:centerY)
            self.backgroundImageView.transform = CGAffineTransform(scaleX: kScale, y: kScale)
        } else if (offsetY > 0 && offsetY <= self.bounds.size.height - kNavigationBarHeight) {
            // 上拉
            
            /**
            // 改变背景图的位置
            self.top = -offsetY / 2;
            // 每移动1像素需要改变的比例
            let kEachPixel:CGFloat = (1 - self.kHeaderMinWidth / self.kHeaderWidth) / (self.bounds.size.height - kNavigationBarHeight);
            let kScale:CGFloat = 1 - offsetY * kEachPixel
            self.headerImageView.transform = CGAffineTransform(scaleX: kScale, y: kScale)
            **/
        }
        
        let reachtop:Bool = scrollView.contentOffset.y > 0 ? true : false
        self.block?(reachtop)
        
        //self.fixHeaderImageViewWithReachtop(reachtop: reachtop)
        self.resetAboveHeaderViewFrame()

    
    }
    
    /**
     * 头像的点击回调方法
     */
    func pressHeaderImageWithBlock(block:@escaping PressHeaderBlock){
        
        
        self.navigationBarHeaderImageView.isUserInteractionEnabled = true
        let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(pressHeaderAction(sender:)))
        
        tap.numberOfTapsRequired = 1
        self.navigationBarHeaderImageView.addGestureRecognizer(tap)
        
        
        let tap1:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(pressHeaderAction(sender:)))
        tap1.numberOfTapsRequired = 1
        self.aboveHeaderView.addGestureRecognizer(tap1)

        if let win = UIApplication.shared.keyWindow {
            
            win.addSubview(self.aboveHeaderView)
            
        }
        
        self.pressBlock? = block
    
    }
    
    
    /** 监听scrollView是否滚动到顶部
     * @param reachtop: YES 已经滚动到顶部, NO 在顶部以下
     */
    func scrollViewStateChangeWithBlock(block:@escaping ReachtopBlock){
       self.block? = block
    }
    
    

    // mark - 临界值调整headerImageView
    func fixHeaderImageViewWithReachtop(reachtop:Bool) {
        if (self.viewController?.navigationController != nil) {
            if (reachtop) {
                self.aboveHeaderView.isHidden = true
                self.headerImageView.isHidden = true
                // 移到navigationBar上
                let titleView:UIView = UIView.init()
                titleView.size = CGSize(width:self.kHeaderMinWidth,height:self.kHeaderMinWidth)
                titleView.backgroundColor = UIColor.clear
                self.navigationBarHeaderImageView.centerY = self.kHeaderMinWidth / 2 - 3
                titleView.addSubview(self.navigationBarHeaderImageView)
                self.viewController?.navigationItem.titleView = titleView
            } else {
                self.aboveHeaderView.isHidden = false
                self.headerImageView.isHidden = false
                // 从navigationBar上移除
                self.navigationBarHeaderImageView.removeFromSuperview()
                self.viewController?.navigationItem.titleView = nil
               
            }
        }
    }
    
    func resetAboveHeaderViewFrame (){
        if (self.aboveHeaderView.superview == nil) {
            if let win = UIApplication.shared.keyWindow {
                win.addSubview(self.aboveHeaderView)
            }
        }
        let frameOnWindow:CGRect = self.headerImageView.convert(self.headerImageView.bounds, to: nil)
        if (frameOnWindow.origin.x != 0) {
            self.aboveHeaderView.frame = frameOnWindow
        }
    }
    
    
    // mark - 点击方法
    @objc func pressHeaderAction(sender:UITapGestureRecognizer ) {
        self.pressBlock?()
        
    }
    deinit {
        if (self.aboveHeaderView.superview != nil) {
            self.aboveHeaderView.removeFromSuperview()
        }
    }

}
